package com.tamo.ppresta.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

/**
 * @author yeyang
 * @name ppresta
 * @class name：com.tamo.ppresta.util
 * @class describe
 * @time 2022/12/21 22:18
 * @change
 * @chang time
 * @class describe
 */
public class PhoneHelperUtils {
    /**
     * （1）IMEI(International Mobile Equipment Identity,国际移动身份识别码)：
     * 是由15位数字组成的”电子串号”，其组成结构为TAC（6位数字）+FAC（两位数字）+SNR（6位数字）+SP （1位数字）。
     * 它与每台手机一一对应，而且该码是全世界唯一的。每一只手机在组装完成后都将被赋予一个全球唯一的一组号码，
     * 这个号码从生产到交付使用都将被制造生产的厂商所记录。 IMEI码贴在手机背面的标志上，并且读写于手机内存中。
     * 它也是该手机在厂家的”档案”和”身份证号”。
     * （2）IMSI(International Mobile Subscriber Identification Number,国际移动用户识别码)：
     * 是区别移动用户的标志，储存在SIM卡中，可用于区别移动用户的有效信息。其总长度不超过15位，
     * 同样使用0～9的数字。其中MCC是移动用户所属国家代号，占3位数字，中国的MCC规定为460；MNC是移动网号码，最多由两位数字组成，
     * 用于识别移动用户所归属的移动通信网；MSIN是移动用户识别码，用以识别某一移动通信网中的移动用户。
     */
    private static PhoneHelperUtils mPhoneHelper;
    private TelephonyManager tm;
    private Context mContext;
    String device_model = Build.MODEL; // 设备型号 。
    private static TelephonyManager telephonyManager;
    /**
     * 国际移动用户识别码
     */
    private String IMSI;

    private PhoneHelperUtils(Context context) {
        mContext = context;
        tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    }

    public static PhoneHelperUtils getInstance(Context context) {
        if (mPhoneHelper == null) {
            synchronized (PhoneHelperUtils.class) {
                if (mPhoneHelper == null) {
                    mPhoneHelper = new PhoneHelperUtils(context);
                }
            }
        }
        return mPhoneHelper;
    }

    /**
     * 获取设备名称
     *
     * @return
     */
    public static String getServiceName() {
        return Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }


    /**
     * 获取手机型号
     *
     * @return
     */
    public static String getModel() {
        return android.os.Build.MODEL;
    }

    /**
     * Firmware/OS 版本号
     *
     * @return
     */
    public static String getVersionRelease() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * SDK版本号
     *
     * @return
     */
    public static int getSdkApi() {
        return android.os.Build.VERSION.SDK_INT;
    }

    public static String getWifiName(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        return wifiInfo.getSSID().replace("\"", "").replace("<", "").replace(">", "");
    }

    /**
     * 获取设备卡槽数
     */
    public static int getSimCardCount(Context context) {
        TelephonyManager mTelephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        Class cls = mTelephonyManager.getClass();
        try {
            Method mMethod = cls.getMethod("getSimCount");
            mMethod.setAccessible(true);
            return (int) mMethod.invoke(mTelephonyManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return -1;
    }


    /**
     * 判断设备有效的Sim卡数
     */
    public static int getAvailableSimCardCount(Context context) {
        int count = 0;
        SubscriptionManager mSubscriptionManager = SubscriptionManager.from(context);
        for (int i = 0; i < getSimCardCount(context); i++) {
            SubscriptionInfo sir = mSubscriptionManager
                    .getActiveSubscriptionInfoForSimSlotIndex(i);
            if (sir != null) {
                count++;
            }
        }
        return count;
    }


    /**
     * 获取手机屏幕分辨率
     *
     * @param activity
     * @return
     */
    public static String DisplayMetrics(Activity activity) {
        android.util.DisplayMetrics dm = new android.util.DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        //获得手机的宽度和高度像素单位为px
        return "DisplayMetrics:" + dm.widthPixels + "* " + dm.heightPixels;
    }


    /**
     * 获取当前系统语言
     *
     * @param activity
     * @return
     */
    public static String getLanguage(Activity activity) {
        Locale locale = activity.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        return language;
    }


    // 获取手机CPU信息
    public static String getCpuInfo() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        String[] cpuInfo = {"", ""}; // 1-cpu型号 //2-cpu频率
        String[] arrayOfString;
        try {
            FileReader fr = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            for (int i = 2; i < arrayOfString.length; i++) {
                cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
            }
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
            cpuInfo[1] += arrayOfString[2];
            localBufferedReader.close();
        } catch (Exception e) {
        }
        return "1-cpu型号:" + cpuInfo[0] + "2-cpu频率:" + cpuInfo[1];
    }


    /**
     * 去掉 +86|86 短信中心号和手机号码
     *
     * @param str
     * @return
     */
    public static String getSub(String str) {
        String subStr = "";
        try {
            if (str == null) {
                return "";
            }
            int len = str.length();
            if (len > 11) {
                subStr = str.substring(len - 11);
            } else {
                subStr = str;
            }
        } catch (Exception ioe) {

        }
        return subStr;
    }

    /**
     * IMEI：international mobile Equipment identity手机唯一标识码
     *
     * @return
     */
    public String getImei(Context context) {
        return tm.getDeviceId();
    }


    /**
     * 获取手机IMSI号
     */
    public static String getIMSI(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = mTelephonyMgr.getSubscriberId();
        return imsi;
    }


    /**
     * 获取手机号 取出MSISDN，很可能为空
     *
     * @return
     */
    public String getPhone() {
        return tm.getLine1Number();
    }

    /**
     * ICCID:ICC identity集成电路卡标识，这个是唯一标识一张卡片物理号码的
     *
     * @return
     */
    public String getIccid() {
        if (isSimReady(mContext)) {
            return tm.getSimSerialNumber();
        }
        return "";
    }

    /**
     * IMSI 全称为 International Mobile Subscriber Identity，中文翻译为国际移动用户识别码。
     * 它是在公众陆地移动电话网（PLMN）中用于唯一识别移动用户的一个号码。在GSM网络，这个号码通常被存放在SIM卡中
     *
     * @return
     */
    public String getSubscriberId() {
        if (isSimReady(mContext)) {
            return tm.getSubscriberId();
        }
        return "";
    }


    /**
     * 获取电话号码
     */
//    public static String getNativePhoneNumber() {
//        String NativePhoneNumber=null;
//        NativePhoneNumber=telephonyManager.getLine1Number();
//        return NativePhoneNumber;
//    }
    public String getMNC() {
        String imsi = getSubscriberId();
        if (imsi != null && !imsi.equals("")) {
            return imsi.substring(0, 4);
        }
        return "";
    }


    /**
     * 判断SIM卡是否准备好
     *
     * @param context
     * @return
     */
    public boolean isSimReady(Context context) {
        try {

            int simState = tm.getSimState();
            if (simState == TelephonyManager.SIM_STATE_READY) {
                return true;
            }
        } catch (Exception e) {
            Log.w("PhoneHelper", "021:" + e.toString());
        }
        return false;
    }

    /**
     * 获取当前网络状况
     *
     * @return 如果网络已经连接，并且可用返回true, 否则false
     */
    public static boolean getNetworkState(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo networkinfo = connectivity.getActiveNetworkInfo();
                if (networkinfo != null) {
                    if (networkinfo.isAvailable() && networkinfo.isConnected()) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * 判断是否模拟器。如果返回TRUE， 则当前是模拟器,模拟器IMEI是：00000000000000 运营商不让支付
     *
     * @param context
     * @return
     */
    public boolean isEmulator(Context context) {
        try {
            String imei = tm.getDeviceId();
            if (imei != null && imei.equals("000000000000000")) {
                return true;
            }
            return (Build.MODEL.equals("sdk"))
                    || (Build.MODEL.equals("google_sdk"));
        } catch (Exception ioe) {
            Log.w("PhoneHelper", "009:" + ioe.toString());
        }
        return false;
    }

    /**
     * 获取当前APP名称和版本号
     *
     * @param context
     * @return
     * @throws Exception
     */
    public static String getAppInfo(Context context) {
        context = context.getApplicationContext();
        String applicationName = "";
        String versionName = "";
        String packageName = "";
        int versionCode;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);

            applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
            versionName = packageInfo.versionName;
            packageName = packageInfo.packageName;
            versionCode = packageInfo.versionCode;
            return "applicationName：" + applicationName + " packageName:" + packageName + " versionName:" + versionName + "  versionCode:" + versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前APP名称和版本号
     *
     * @param context
     * @return applicationName  packageName versionName versionCode
     */
    public static Map<String, String> getAppInfoMap(Context context) {
        String applicationName = "";
        String versionName = "";
        String packageName = "";
        int versionCode;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            ApplicationInfo applicationInfo = packageManager
                    .getApplicationInfo(context.getPackageName(), 0);

            applicationName = (String) packageManager
                    .getApplicationLabel(applicationInfo);
            versionName = packageInfo.versionName;
            packageName = packageInfo.packageName;
            versionCode = packageInfo.versionCode;
            Map<String, String> map = new HashMap<String, String>();
            map.put("appName", applicationName);
            map.put("packageName", packageName);
            map.put("versionName", versionName);
            map.put("versionCode", versionCode + "");
            return map;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取MetaDataValue
     *
     * @param name
     * @param def
     * @return
     */
    public String getMetaDataValue(String name, String def) {
        String value = getMetaDataValue(name);
        return (value == null) ? def : value;
    }

    private String getMetaDataValue(String name) {
        Object value = null;
        PackageManager packageManager = mContext.getPackageManager();
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = packageManager.getApplicationInfo(mContext.getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo != null && applicationInfo.metaData != null) {
                value = applicationInfo.metaData.get(name);
            }
        } catch (Exception e) {
        }
        return value.toString();
    }


    /**
     * 获取设备唯一标识 UUID
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * Android客户端获取IP地址
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {

        }
        return null;
    }


    /**
     * 获取手机服务商信息
     */
    public String getProvidersName() {
        String ProvidersName = "N/A";
        try {
            IMSI = telephonyManager.getSubscriberId();
            // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。
            System.out.println(IMSI);
            if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
                ProvidersName = "中国移动";
            } else if (IMSI.startsWith("46001")) {
                ProvidersName = "中国联通";
            } else if (IMSI.startsWith("46003")) {
                ProvidersName = "中国电信";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ProvidersName;
    }


    /**
     * 获取一些简单的信息,软件版本，手机版本，型号等信息存放在HashMap中
     *
     * @return
     */
    public static HashMap<String, String> obtainSimpleInfo(Context context) {
        HashMap<String, String> map = new HashMap<>();
        PackageManager mPackageManager = context.getPackageManager();
        PackageInfo mPackageInfo = null;
        try {
            mPackageInfo = mPackageManager.getPackageInfo(
                    context.getPackageName(), PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        map.put("versionName", mPackageInfo.versionName);
        map.put("versionCode", "" + mPackageInfo.versionCode);
        map.put("MODEL", "" + Build.MODEL);
        map.put("SDK_INT", "" + Build.VERSION.SDK_INT);
        map.put("PRODUCT", "" + Build.PRODUCT);
        map.put("MOBLE_INFO", getMobileInfo());
        return map;
    }

    /**
     * 获取手机信息  HomiNote 6.0
     *
     * @return
     */
    public static String getMobileInfo() {
        StringBuffer sb = new StringBuffer();
        try {
            // 利用反射获取 Build 的所有属性
            Field[] fields = Build.class.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String name = field.getName();
                String value = field.get(null).toString();
                sb.append(name + "=" + value);
                sb.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    /**
     * 根据IP地址获取MAC地址
     *
     * @return
     */
    public static String getLocalMacAddressFromIp() {
        String strMacAddr = null;
        try {
            //获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        } catch (Exception e) {

        }

        return strMacAddr;
    }

    /**
     * 获取移动设备本地IP
     *
     * @return
     */
    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            //列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {//是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();//得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {

            e.printStackTrace();
        }
        return ip;
    }
} 